package com.oracle.zebrafreelytraveling.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResBase;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResCircle;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResState;
import com.oracle.zebrafreelytraveling.data.bean.Circle;
import com.oracle.zebrafreelytraveling.data.bean.Place;
import com.oracle.zebrafreelytraveling.data.bean.User;
import com.oracle.zebrafreelytraveling.net.HttpManager;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.HeaderAndFooterWrapper;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.LoadMoreWrapper;
import com.oracle.zebrafreelytraveling.utils.StringUtil;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;
import com.oracle.zebrafreelytraveling.utils.UserUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yydcnjjw on 2017/8/4.
 * 圈子介绍界面
 */

public class CircleIntroActivity extends AppCompatActivity {

    public static final int PREVIEW = 0;
    public static final int SKIP = 1;

    public static final String CIRCLE_INFO = "circleInfo";
    private ResCircle.DataBean circleInfo;
    private RecyclerView mCircleIntroRecycle;
    private CommonAdapter<User> mCircleIntroAdapter;
    private LoadMoreWrapper mLoadMoreWrapper;
    private HeaderAndFooterWrapper mHFWrapper;
    private List<User> mUserList;

    private View mCircleItemHeader;
    private SimpleDraweeView mCircleIntroHeadimg;
    private TextView mCircleIntroName;
    private TagFlowLayout mCircleIntroLabel;
    private TextView mCircleIntroSite;
    private TextView mCircleIntroContent;
    private Button mCircleIntroJoin;

    private SimpleDraweeView mUserHeadImg;

    private ViewHolder mLoadViewHolder;

    private Disposable mDisposable;

    private boolean isListNull = false;
    private int page;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_intro);
        getIntentData();
        initView();
        initCircleIntro();
    }

    private void initView(){
        mCircleIntroRecycle = (RecyclerView) findViewById(R.id.circle_user_list);

        mCircleItemHeader = LayoutInflater.from(this).inflate(R.layout.head_item_circle_intro, null);
        mCircleIntroHeadimg = (com.facebook.drawee.view.SimpleDraweeView) mCircleItemHeader.findViewById(R.id.circle_intro_headimg);
        mCircleIntroName = (TextView) mCircleItemHeader.findViewById(R.id.circle_intro_name);
        mCircleIntroLabel = (TagFlowLayout) mCircleItemHeader.findViewById(R.id.circle_intro_label);
        mCircleIntroSite = (TextView) mCircleItemHeader.findViewById(R.id.circle_intro_site);
        mCircleIntroContent = (TextView) mCircleItemHeader.findViewById(R.id.circle_intro_content);
        mCircleIntroJoin = (Button) mCircleItemHeader.findViewById(R.id.circle_intro_join);

        mCircleIntroJoin.setOnClickListener(v -> joinCircle());
        initRecycleView();
    }

    private void initRecycleView(){
        mCircleIntroRecycle.setLayoutManager(new LinearLayoutManager(this));
        mUserList = new ArrayList<>();
        mCircleIntroAdapter = new CommonAdapter<User>(this, R.layout.item_circle_user, mUserList) {
            @Override
            protected void convert(ViewHolder holder, User user, int position) {
                mUserHeadImg = holder.getView(R.id.circle_intro_user_headimg);
                mUserHeadImg.setImageURI(Constant.DOWNLOAD_URL + user.getHeadImg());
                holder.setText(R.id.circle_intro_user_name, user.getName());
            }
        };
        mCircleIntroAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                //点击进入个人信息界面
                PersonalCenterActivity.startPersonalCenterActivity(CircleIntroActivity.this, mUserList.get(position - 1),
                        PersonalCenterActivity.OTHER);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mLoadMoreWrapper = new LoadMoreWrapper(mCircleIntroAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.footer_loading);
        mLoadMoreWrapper.setOnLoadMoreListener(viewHolder -> {
            mLoadViewHolder = viewHolder;
            if (!isListNull){
                getUserInfoList(PREVIEW);
            } else {
                viewHolder.getConvertView().setVisibility(View.GONE);
            }
        });
        mHFWrapper = new HeaderAndFooterWrapper(mLoadMoreWrapper);
        mHFWrapper.addHeaderView(mCircleItemHeader);
        mCircleIntroRecycle.setAdapter(mHFWrapper);
    }

    private void getIntentData(){
        Intent intent = getIntent();
        circleInfo = (ResCircle.DataBean) intent.getSerializableExtra(CIRCLE_INFO);
    }

    /**
     * 初始化圈子界面
     */
    private void initCircleIntro(){
        Circle circle = circleInfo.getCircle();
        Place place = circleInfo.getPlace();
        mCircleIntroHeadimg.setImageURI(Constant.DOWNLOAD_URL + circle.getHeadImg());
        mCircleIntroName.setText(circle.getName());
        String[] labelList = StringUtil.formatLabelList(circle.getLabel());
        if (labelList != null){
            mCircleIntroLabel.setAdapter(new TagAdapter<String>(labelList) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.tag_card_label_tv,
                            mCircleIntroLabel, false);
                    tv.setText(s);
                    return tv;
                }
            });
        }
        mCircleIntroSite.setText(place.getPlaceName());
        mCircleIntroContent.setText(circle.getIntro());
    }

    private void getUserInfoList(int type){
        HttpManager.getInstance().getService(Constant.BASE_URL)
                .getUserList(Constant.CIRCLE_TYPE, circleInfo.getCircle().getCircleId(), page, Constant.MAX_PAGE)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResBase<List<User>>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }
                    @Override
                    public void onNext(@NonNull ResBase<List<User>> userResBase) {
                        if (userResBase.getCode().equals(Constant.REQUEST_SUCCESS)){
                            mUserList.addAll(userResBase.getData());
                            DataSupport.saveAll(mUserList);
                            isListNull = false;
                        } else {
                            ToastUtil.showToast(userResBase.getMessage());
                            isListNull = true;
                            return;
                        }
                        if (type == SKIP){
                            getUserInfoList(SKIP);
                        }

                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("CircleIntroError", e.getMessage());
                        mLoadViewHolder.getConvertView().setVisibility(View.GONE);
                        isListNull = true;
                    }
                    @Override
                    public void onComplete() {
                        mHFWrapper.notifyDataSetChanged();
                        mLoadViewHolder.getConvertView().setVisibility(View.GONE);
                    }
                });
        page++;
    }

    private void joinCircle(){
        if (!UserUtil.isLogin()){
            return;
        }
        User user = UserUtil.getUserInfoFromSP();
        HttpManager.getInstance().getService(Constant.BASE_URL)
                .joinCircle(user.getUserId(), circleInfo.getCircle().getCircleId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResState>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResState resState) {
                        if (resState.getCode().equals(Constant.REQUEST_SUCCESS)){
                            ChatActivity.startChatActivity(CircleIntroActivity.this,
                                    Constant.GROUP_MESSAGE, circleInfo.getCircle().getCircleId());
                            getUserInfoList(SKIP);
                        }
                        ToastUtil.showToast(resState.getMessage());
                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("CircleIntroError", e.getMessage());
                    }
                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    public static void startCircleIntroActivity(Activity activity, ResCircle.DataBean dataBean){
        Intent intent = new Intent(activity, CircleIntroActivity.class);
        intent.putExtra(CIRCLE_INFO, dataBean);
        activity.startActivity(intent);
    }
}
